﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsForms
{
    class DbHelper
    {
        public static readonly string conString = "server = .; uid = sa; pwd = seventeen111; database = Blogs";
        /// <summary>
        /// 获取数据表
        /// </summary>
        /// <param name="cmdString"></param>
        /// <returns></returns>
        public static DataTable GetTable(string cmdString)
        {
            SqlConnection connection = new SqlConnection(conString);

            SqlDataAdapter dataAdapter = new SqlDataAdapter(cmdString, conString);

            connection.Open();

            DataTable table = new DataTable();

            dataAdapter.Fill(table);

            return table;
        }
        /// <summary>
        /// 增删改
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int AddOrEditOrDeleSave(string sql)
        {
            SqlConnection connection = new SqlConnection(conString);

            SqlCommand command = new SqlCommand(sql, connection);

            connection.Open();

            return command.ExecuteNonQuery();
        }
        /// <summary>
        /// 与数据库连接，查询用户和密码是否存在数据库内
        /// </summary>
        /// <param name="txtname"></param>
        /// <param name="txtpwd"></param>
        /// <returns></returns>
        public static SqlDataReader GetReader(string txtname,string txtpwd)
        {
            SqlConnection connection = new SqlConnection(conString);

            SqlCommand command = new SqlCommand("select* from Users where Username = @Username and Password = @Password", connection);

            command.Parameters.AddWithValue("@Username", txtname);

            command.Parameters.AddWithValue("@Password", txtpwd);

            connection.Open();

            return command.ExecuteReader();
        }
        /// <summary>
        /// 判断用户是否存在于数据库内
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataSet GetDataSet(string sql)
        {
            SqlConnection connection = new SqlConnection(conString);

            connection.Open();

            SqlCommand command = new SqlCommand(sql, connection);

            SqlDataAdapter dataAdapter = new SqlDataAdapter
            {
                SelectCommand = command
            };

            DataSet dataSet = new DataSet();

            dataAdapter.Fill(dataSet);

            return dataSet;
        }
    
}
}
